package cn.wolfcode.luowowo.website.web.controller;


import cn.wolfcode.luowowo.cache.util.RedisKeys;
import cn.wolfcode.luowowo.common.exception.LogicException;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import cn.wolfcode.luowowo.website.web.annotation.RequireLogin;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@Controller
public class LoginController {

    @Reference  //2 不在同一个服务需要使用rpc
    private IUserInfoService userInfoService;

    @RequireLogin  //需要登录检查
    @RequestMapping("/hello")
    @ResponseBody
    public Object hello(Long id){
        return userInfoService.get(id);
    }



    //手机号码唯一性校验
    @RequestMapping("/checkPhone")
    @ResponseBody
    public Object checkPhone(String phone){

        return !userInfoService.checkPhone(phone);
    }

    //发送验证码
    @RequestMapping("/sendVerifyCode")
    @ResponseBody
    public Object sendVerifyCode(String phone){
        userInfoService.sendVerifyCode(phone);
        return AjaxResult.SUCCESS;
    }


    //用户注册
    @RequestMapping("/userRegist")
    @ResponseBody
    public Object userRegist(String phone, String nickname, String password, String rpassword, String verifyCode){
        //存在一个问题：需要给用户看的异常， 与 代码系统异常(bug)异常混在一起
        userInfoService.userRegist( phone,  nickname,  password,  rpassword,  verifyCode);
        return AjaxResult.SUCCESS;
    }

    //用户登录
    @RequestMapping("/userLogin")
    @ResponseBody
    public Object userLogin(String username, String password, HttpServletResponse resp){
        String token = userInfoService.userLogin( username,  password);
        //8：创建cookie对象，
        //注意：设置cookie存活时间：30分钟 /共享路径
        //存活时间：30分钟
        //共享路径
        //9：使用response对象将cookie对象传输到浏览器中
        CookieUtil.addCookie("token", token,RedisKeys.USER_LOGIN_TOKEN.getTime().intValue(), resp);

        return AjaxResult.SUCCESS;
    }
}
